﻿Imports System.Threading

Class PrinterThread
    Public StateText As Label
    Dim HS As New HttpServer

    Public m_oPollingThread As New Thread(New System.Threading.ThreadStart(AddressOf PollProcess))

    Public Sub Thead_Start()
        If m_oPollingThread.ThreadState.ToString.Equals("Unstarted") Then
            m_oPollingThread.Start()
        Else
            m_oPollingThread.Resume()
        End If
    End Sub

    Public Sub Thead_Pause()
        m_oPollingThread.Suspend()
    End Sub

    Public Sub Thead_Close()
        If m_oPollingThread.ThreadState.ToString.Equals("SuspendRequested, WaitSleepJoin") Or
                m_oPollingThread.ThreadState.ToString.Equals("Suspended") Then
            m_oPollingThread.Resume()
        End If

        m_oPollingThread.Abort()
    End Sub

    Public Sub PollProcess()
        ' Loops, until killed by OnStop.
        Console.WriteLine("PollingService service polling thread started.")
        Do
            ' Wait...
            PollingPass()
            'Me.Invoke_Thread("就绪")
            System.Threading.Thread.Sleep(My.Settings.WM_TIMER) ' 1000 = 1 seconds
        Loop
    End Sub

    Private Sub PollingPass()
        Try

            Me.Invoke_Thread("获取远程数据")
            'Console.WriteLine("poll")
            If (HS.RequestData()) Then
                Dim PD As New PrinterDrawing
                PD.DocIteration(HS.DocLists)
                Me.Invoke_Thread(HS.Msg)
            Else
                Me.Invoke_Thread(HS.Msg)
            End If

        Catch ex As System.Exception
            Console.WriteLine("PollingService encountered an error '" &
            ex.Message & "'", EventLogEntryType.Error)
            Console.WriteLine("PollingService service Stack Trace: " &
            ex.StackTrace, EventLogEntryType.Error)

            Me.Invoke_Thread(ex.Message)
            m_oPollingThread.Suspend()
        End Try
    End Sub

    Delegate Sub My_Delegate(ByVal state As String)
    Public Sub Invoke_Thread(ByVal state As String)
        Dim hander As New My_Delegate(AddressOf ShowState)
        StateText.Dispatcher.Invoke(hander, state)
    End Sub

    Public Sub ShowState(ByVal state As String)
        StateText.Content = state
    End Sub

    Public Sub SetLabel(ByRef label As Label)
        StateText = label
    End Sub

End Class